// pages/site/addsite/index.js
const app = getApp() // 引入app
import _request from '../../utils/request.js'
// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk
const area = require('../../utils/area');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:"add",
    dataEdit:{},
    imgUrl: app.globalData.imgUrl, //全局img路径
    bool: false,
    city: '省、市、区',
    show: false,
    name:null,
    phone:null,
    detailAddress:null,
    areaList: area.areaList,
  },


  // 展示选择城市
  showmolde() {
    this.setData({
      show: true
    });
  },

  // 关闭选择城市
  onClose() {
    this.setData({
      show: false
    });
  },

  // 完成选择城市，发送请求
  onFirm(e) {
    this.setData({
      show: false,
      city: e.detail.values.map(item=>{
        return item.name 
      })
    });
  },
  inputEdit(e){
    let name = e.currentTarget.dataset.name;
    this.data[name] = e.detail.value;
    console.log(this.data)
  },
  edit(){
    _request.postObj('/receiveAndDeliver/updateReceiveAndDeliverAddressById', {
      userId: wx.getStorageSync('userId'),
      id:this.data.dataEdit.id,
      receiveStatus:Number(this.data.bool),
      name:this.data.name,
      phone:this.data.phone,
      detailAddress:this.data.detailAddress,
      province:this.data.city[0],
      city:this.data.city[1],
      region:this.data.city[2],
      regionalCode:'0'
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        console.log(res.data)
        wx.navigateBack({
          url: '/pages/site/index',
        })
      }
    })
  },
  onAdd(){
    ///receiveAndDeliver/saveReceiveAndDeliverAddress
    _request.postObj('/receiveAndDeliver/saveReceiveAndDeliverAddress', {
      userId: wx.getStorageSync('userId'),
      receiveStatus:Number(this.data.bool),
      name:this.data.name,
      phone:this.data.phone,
      detailAddress:this.data.detailAddress,
      province:this.data.city[0],
      city:this.data.city[1],
      region:this.data.city[2],
      regionalCode:'0'
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        console.log(res.data)
        wx.navigateBack({
          url: 'pages/site/index',
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon:'none'
        })
      }
    })
  },
  //设置默认
  setDefault() {
    this.setData({
      bool: !this.data.bool
    })
  },

  // 获取用户定位
  getUserLocation() {
    let vm = this
    wx.getSetting({
      success(res) {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 2000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 2000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          // 不存在就获取权限
          vm.getLocation()
        } else {
          //调用wx.getLocation的API
          vm.getLocation()
        }
      }
    })
  },
  // 授权定位权限
  getLocation() {
    var _this = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude;
        let longitude = res.longitude;
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
          key: 'MBEBZ-6VQCP-EYSDK-LT7FQ-2LNUS-G4BTN'
        });
        // 经纬度转城市
        qqmapsdk.reverseGeocoder({
          //位置坐标
          location: {
            latitude: latitude,
            longitude: longitude
          },

          //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
          success: function (res) { //成功后的回调
            var res = res.result;
            var mks = [];
            mks.push({ // 获取返回结果，放到mks数组中
              title: res.address,
              id: 0,
              latitude: res.location.lat,
              longitude: res.location.lng,
              iconPath: './resources/placeholder.png', //图标路径
              width: 20,
              height: 20,
              callout: { //在markers上展示地址名称，根据需求是否需要
                content: res.address,
                color: '#000',
                display: 'ALWAYS'
              },
              ad_info: res.ad_info,
              address_component: res.address_component,
            });
            _this.setData({ //设置markers属性和地图位置poi，将结果在地图展示
              markers: mks,
              city: res.ad_info.province + ',' + res.ad_info.city + ',' + res.ad_info.district,
            });
          },
          fail: function (error) {
            console.error(error);
          },
          complete: function (res) {}
        })
        // 储存地址
        wx.setStorageSync('location', res)
      },
      fail: function (error) {
        console.log(error, 'error');
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.setData({
      type:options.type
    })
    if(options.data){
      console.log()
      wx.setNavigationBarTitle({
    　　　　title: '修改地址'
    　　})
      let dataEdit = JSON.parse(options.data)
      this.setData({
        dataEdit:dataEdit,
        name:dataEdit.name,
        phone:dataEdit.phone,
        detailAddress:dataEdit.detailAddress,
        bool:Boolean(dataEdit.receiveStatus),
        city:[dataEdit.province,dataEdit.city,dataEdit.region],
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})